﻿import os
import nuke
import nukescripts
import sys
if sys.version>'3':
    from PySide2.QtGui import *
    from PySide2.QtCore import *
    from PySide2.QtWidgets import *
else:
    from PySide2.QtGui import *
    from PySide2.QtCore import *
    from PySide2.QtWidgets import *

from ParmControl import ParmControlWindow
from exportmov import ExportMov
from submitDeadline import DeadlineWindow
from tools.replace_diver_path import ReplaceDirver
"""
nuke菜单栏注册文件，可以对nuke的菜单栏进行自定义添加
"""


def autoReplacePath():
    import os
    info = {}
    n = nuke.thisNode()
    if n.Class() == 'Read':
        f = n['file'].value()
        if f.endswith('config.json'):
            with open(f, 'r') as r:
                info = eval(r.read())
    if info:
        data = info.get('data', {})
        print('path_data:',data)
        for i in nuke.allNodes():
            if i.Class() == 'Read':
                label = i['label'].value()
                if label:
                    value = data.get(label, {})
                    scr_path = value.get('scr_path')
                    cgtw_file_dir_path = value.get('cgtw_file_dir_path')
                    _, file_all_name = os.path.split(scr_path)
                    cgtw_path = os.path.join(cgtw_file_dir_path, file_all_name).replace('\\', '/')
                    i['file'].setValue(cgtw_path)


def init_UI():
    if nuke.GUI:
        menubar = nuke.menu("Nodes")
        mz_menu = menubar.addMenu("MZ_NUKE_Tool", 'nuker.jpg')
        mz_menu.addCommand('ReplaceDiskPath', "replaceDiskPath()")
        mz_menu.addCommand("ReadBatch", "read_window()")
        mz_menu.addCommand("ExportMov", "export_window()")
        mz_menu.addCommand("CompressImg", "compress()")
        mz_menu.addCommand("AutoShuffle", "auto_shuffle()")
        # mz_menu.addCommand("Deadline", "submit_job()")

        # mz_menu.addCommand("Pack/pack selected nodes", "testModalPanel()")
        # mz_menu.addCommand("Format/1920 1080 25", "format_hd1080()")
        # mz_menu.addCommand("Format/2048 1152 25", "format_2048x1152()")
        nuke.addKnobChanged(autoReplacePath, nodeClass='Read')

def replaceDiskPath():
    app = qApp
    global rp
    try:
        rp.close()
        rp.deleteLater()
    except:
        pass

    rp = ReplaceDirver()
    rp.show()



def read_window():
    app=qApp
    global pw
    try:
        pw.close()
        pw.deleteLater()
    except:
        pass
    #win=app.activeWindow()
    pw=ParmControlWindow(None)
    pw.show()
    # root = nuke.Root()
        # comment = root['label'].value()
        # comment_list = comment.split('%')
        # if len(comment_list)==3:
        #     pane = nuke.getPaneFor('Properties.1')
        #     nukescripts.panels.registerWidgetAsPanel('ParmControlWindow', 'MZ_NUKE', 'uk.co.thefoundry.ParmControlWindow', True).addToPane(pane)
        # else:
        #     nuke.message("打开失败")


def export_window():
    # # app = qApp
    # global emov
    # try:
    #
    #     emov.close()
    #     emov.deleteLater()
    # except:
    #     pass
    # #win = app.activeWindow()
    # #emov = ExportMov(win)
    # emov = ExportMov(None)
    # emov.show()

    global emov
    try:
        emov.show()
        # dialog.setHidden(False)
        # emov.setHidden(False)
    except :

        emov = ExportMov(None)
        emov.show()


def compress():
    sn = nuke.selectedNodes()
    for i in sn:
        if i.Class() == 'Read':
            file_path = i['file'].value()
            dir_path,file_long_name=os.path.split(file_path)
            file_name,file_type=os.path.splitext(file_long_name)
            new_file_long_name=file_name+'_compress'+'.jpeg'
            new_file_path=os.path.join(dir_path,new_file_long_name).replace('\\','/')
            write=nuke.createNode('Write')
            write.setInput(0,i)
            write['file'].setValue(new_file_path)
            nuke.execute(write.name(),1,1,1)

def auto_shuffle():
    sn = nuke.selectedNode()
    assert sn ,'选择一个节点好么'
    x = sn.xpos()
    y = sn.ypos()

    cs = sn.channels()
    layers = sorted(list(set(i.split('.')[0] for i in cs)))

    master_layer_prex = ['diffuse', 'specular', 'sss', 'occ']

    occ_list = []
    diffuse_list = []

    other_list = []
    for c in layers:
        if c.lower().count('diffuse') > 0:
            diffuse_list.append(c)
        elif c.lower().count('specular') > 0:
            diffuse_list.append(c)  # 也算diffuse里面
        elif c.lower().count('occ') > 0:
            occ_list.append(c)
        elif c.lower().count('sss') > 0:
            diffuse_list.append(c)  # sss也算diffuse里面
        else:
            other_list.append(c)

    o_merge = None
    d_merge = None
    delta_x = 0
    if occ_list:
        occ_grades = []
        for o in occ_list:
            sf = nuke.createNode('Shuffle')
            sf.setName('Shuffle_' + o)
            sf['postage_stamp'].setValue(1)
            sf.setInput(0, sn)
            sf['in'].setValue(o)
            sf.setXpos(x + delta_x)
            sf.setYpos(y + 150)
            grade = nuke.createNode('Grade')
            grade.setName('Grade_' + o)
            grade.setInput(0, sf)
            grade.setXpos(x + delta_x)
            grade.setYpos(y + 300)
            delta_x += 150

        o_merge = nuke.createNode('Merge')
        o_merge['operation'].setValue('mult')
        o_merge.setXpos(x + delta_x - 150)
        o_merge.setYpos(y + 600)
        for i in range(len(occ_grades)):
            o_merge.setInput(i, occ_grades[i])

    if diffuse_list:
        # delta_x+=150 #先偏移一波
        d_grades = []  # 使用grade来缓解一波

        for d in diffuse_list:
            sf = nuke.createNode('Shuffle')
            sf.setName('Shuffle_' + d)
            sf['postage_stamp'].setValue(1)
            sf.setInput(0, sn)
            sf['in'].setValue(d)
            sf.setXpos(x + delta_x)
            sf.setYpos(y + 150)
            grade = nuke.createNode('Grade')
            grade.setName('Grade_' + d)
            grade.setXpos(x + delta_x)
            grade.setYpos(y + 300)
            grade.setInput(0, sf)
            if d.lower() in ['diffuse', 'sss']:
                d_grades.append(grade)
            delta_x += 150

        d_merge = nuke.createNode('Merge')
        d_merge['operation'].setValue('plus')
        d_merge.setXpos(x + 150)
        d_merge.setYpos(y + 450)
        for g in range(len(d_grades)):
            d_merge.setInput(g, d_grades[g])


def submit_job():
    app = qApp
    global deadlineWindow
    try:
        deadlineWindow.close()
        deadlineWindow.deleteLater()
    except:
        pass
    #win = app.activeWindow()
    #emov = ExportMov(win)
    deadlineWindow = DeadlineWindow()
    deadlineWindow.show()












init_UI()